﻿using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using Sunny.UI;
using Work.API.Dtos;

namespace WinFormsApp1
{
    public partial class LoginForm : UIForm
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        /// <summary>
        /// 登录成功后的用户信息
        /// </summary>
        public LoginDTO? LoggedInUser { get; private set; }

        public LoginForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            
            // 注意：SunnyUI 主题通过窗体和控件的 Style 属性设置，已在 Designer 中设置
        }

        /// <summary>
        /// 登录按钮点击事件
        /// </summary>
        private async void btnLogin_Click(object? sender, EventArgs e)
        {
            // 1. 验证输入
            if (string.IsNullOrWhiteSpace(txtUsername.Text))
            {
                UIMessageBox.ShowWarning("请输入用户名");
                txtUsername.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                UIMessageBox.ShowWarning("请输入密码");
                txtPassword.Focus();
                return;
            }

            // 2. 禁用按钮，防止重复提交
            btnLogin.Enabled = false;

            try
            {
                // 3. 构建请求
                var request = new
                {
                    Username = txtUsername.Text.Trim(),
                    Password = txtPassword.Text
                };

                // 4. 调用API
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync("api/User/Login", content);

                // 5. 读取响应
                response.EnsureSuccessStatusCode();
                var responseJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<LoginDTO>>(
                    responseJson,
                    _jsonOptions
                );

                // 6. 处理结果（兼容不同后端返回风格）
                // 判定成功的条件：
                //  - 后端统一成功码 Code == 100，且 Data 不为空；或
                //  - Data.Success == true（部分实现会返回Success标志）
                if (apiResult?.Data != null && (apiResult.Code == 100 || (apiResult.Data.Success)))
                {
                    // 登录成功
                    LoggedInUser = apiResult.Data;
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    UIMessageBox.ShowError(
                        apiResult?.Message ?? apiResult?.Data?.Message ?? "登录失败"
                    );
                    txtPassword.Clear();
                    txtPassword.Focus();
                }
            }
            catch (HttpRequestException)
            {
                UIMessageBox.ShowError("无法连接到服务器，请检查API服务是否运行");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"登录失败：{ex.Message}");
            }
            finally
            {
                btnLogin.Enabled = true;
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object? sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// 密码框回车键事件
        /// </summary>
        private void txtPassword_KeyDown(object? sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(sender, e);
            }
        }

        /// <summary>
        /// API响应结果封装类
        /// </summary>
        private class ApiResult<T>
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public T? Data { get; set; }
        }
    }
}

